// src/utils/dateUtil.js

/**
 * 日期格式化工具函数 (JavaScript 版本)
 * @param {Date|string|number} date - 可被 Date 解析的时间值
 * @param {string} format - 格式字符串，默认 'YYYY-MM-DD'
 * @returns {string} 格式化后的日期字符串
 */
export function formatDate(date = new Date(), format = 'YYYY-MM-DD') {
    const d = new Date(date);
    if (isNaN(d.getTime())) throw new Error('Invalid date');
  
    const padZero = num => num.toString().padStart(2, '0');
  
    return format
      .replace(/YYYY/g, d.getFullYear())
      .replace(/MM/g, padZero(d.getMonth() + 1))
      .replace(/DD/g, padZero(d.getDate()))
      .replace(/HH/g, padZero(d.getHours()))
      .replace(/mm/g, padZero(d.getMinutes()))
      .replace(/ss/g, padZero(d.getSeconds()));
  }
  
/**
 * 计算年龄的函数
 * @param {Date|string|number} birthDate - 出生日期
 * @returns {number} 年龄
 */
export function calculateAge(birthDate) {
    const today = new Date();
    const birth = new Date(birthDate);
    
    let age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
    }
    
    return age;
}

/**
 * 格式化文件大小
 * @param {number} bytes - 文件大小（字节）
 * @returns {string} 格式化后的文件大小
 */
export function formatFileSize(bytes) {
    if (bytes === null || bytes === undefined || bytes === '') return '';
    bytes = parseInt(bytes);
    if (isNaN(bytes)) return '';
    
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let size = bytes;
    let unitIndex = 0;
    
    while (size >= 1024 && unitIndex < units.length - 1) {
      size /= 1024;
      unitIndex++;
    }
    
    return `${size.toFixed(2)} ${units[unitIndex]}`;
  }